package blog.aop;

import java.text.SimpleDateFormat;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import blog.service.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import blog.dto.TotalInfo;
import blog.entity.Category;
import blog.entity.Menu;
import blog.entity.Tag;
import blog.enums.LinkStatus;

/**
 * 通用资源过滤器
 * 在请求处理之前执行，该方法主要是用于准备通用的资源数据
 */
@Component
public class CommonDataInterceptor implements HandlerInterceptor {
    //文章
    @Resource
    ArticleService articleService;
    //分类
    @Resource
    CategoryService categoryService;
    //评论
    @Resource
    CommentService commentService;
    //标签
    @Resource
    TagService tagService;
    //链接
    @Resource
    LinkService linkService;
    //菜单
    @Resource
    private MenuService menuService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获得网站概况--几乎每个页面都需要的数据
        TotalInfo totalInfo = new TotalInfo();
        totalInfo.setArticleCount(articleService.countArticle());
        totalInfo.setArticleViewCount(articleService.countArticleView());
        totalInfo.setCategoryCount(categoryService.countCategory());
        totalInfo.setCommentCount(commentService.countComment());
        totalInfo.setLinkCount(linkService.countLink(LinkStatus.NORMAL.getValue()));
        totalInfo.setTagCount(tagService.countTag());
        totalInfo.setLastUpdateTime(new SimpleDateFormat("yyyy年MM月dd日").format(articleService.getLastUpdateArticle().getArticleUpdateTime()));
        request.setAttribute("totalInfo", totalInfo);
        //菜单显示
        List<Menu> menuList = menuService.listMenu();
        request.setAttribute("menuList", menuList);
        //分类信息(在framework.jsp中做的显示,用于呈现导航, 正常来说,要限定一下查出来的数量,以免前台挤不下,但本查询暂时没做限定))
        List<Category> categoryList = categoryService.listCategory();
        request.setAttribute("cateList", categoryList);
        //侧边栏显示所有标签
        List<Tag> tagList = tagService.listTag();
        request.setAttribute("tagList", tagList);
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
